package ace.cmp.id.generator.snowflake;

import ace.cmp.id.generator.api.LongIdGenerator;
import ace.cmp.id.generator.snowflake.builder.SnowflakeBuilder;
import ace.cmp.id.generator.snowflake.builder.SnowflakeHostIPBuilder;
import ace.cmp.id.generator.snowflake.builder.SnowflakeManualBuilder;
import ace.cmp.id.generator.snowflake.enums.SnowflakeBuilderEnum;
import ace.cmp.id.generator.snowflake.property.SnowflakeManualProperties;
import ace.cmp.id.generator.snowflake.property.SnowflakeProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author Caspar auto config snowflake sequence
 */
@ConditionalOnProperty(
    value = "ace.cmp.id.generator.snowflake.enable",
    matchIfMissing = true,
    havingValue = "true")
@EnableConfigurationProperties({SnowflakeProperties.class, SnowflakeManualProperties.class})
@Configuration
public class SnowflakeIdGeneratorBootstrapAutoConfig {

  @Bean
  @ConditionalOnMissingBean
  public SnowflakeBuilder snowflakeIdGeneratorBuilder(SnowflakeProperties snowflakeProperties) {
    if (SnowflakeBuilderEnum.MANUAL_BUILDER.equals(snowflakeProperties.getBuilderType())) {
      return new SnowflakeManualBuilder(snowflakeProperties.getManual());
    }
    return new SnowflakeHostIPBuilder();
  }

  @Bean
  @ConditionalOnMissingBean
  public LongIdGenerator snowflakeIdGenerator(SnowflakeBuilder builder) {
    return builder.build();
  }
}
